package com.ruoyi.framework.interceptor;


import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.weixin.Exception.BussnissExecption;
import com.ruoyi.weixin.anno.RequireLogin;
import com.ruoyi.weixin.entity.R;
import com.ruoyi.weixin.entity.User;
import com.ruoyi.weixin.service.UserService;
import com.ruoyi.weixin.untils.BaseContext;
import com.ruoyi.weixin.untils.JWTUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class LoginInterception implements HandlerInterceptor {

    @Autowired
    UserService userService;

    @Autowired
    RedisCache redisCache;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!( handler instanceof HandlerMethod)){
            //静态资源  options
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Class<?> contrllerClass = handlerMethod.getBeanType();
        RequireLogin annotation = contrllerClass.getAnnotation(RequireLogin.class);
        RequireLogin methodAnnotation = handlerMethod.getMethodAnnotation(RequireLogin.class);

        if (annotation==null&&methodAnnotation==null){
            return true;
        }
        System.err.println(request.getRemoteAddr());
        String token = request.getHeader("token");
        if (token==null){
            return false;
        }else {
            String id = JWTUtils.validateToken(token);
            User user = userService.getById(id);

            if (user==null){
                return false;
            }
            log.info("通过");
            return true;
        }

    }
}
